package com.baizhi.aspect;

import com.baizhi.annotation.CmfzLogAnnotation;
import com.baizhi.dao.CmfzLogDao;
import com.baizhi.entity.CmfzAdmin;
import com.baizhi.entity.CmfzLog;
import com.baizhi.util.IPKit;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Method;
import java.util.Date;

/**
 * Created by Administrator on 2019/4/11 0011.
 */
@Configuration
@Aspect
public class CmfzAspect {
    @Autowired
    private CmfzLogDao cmfzLogDao;
    /*用于写日志*/
    private Logger logger= LoggerFactory.getLogger(CmfzAspect.class);


    /*定义切入点*/
    @Pointcut("@annotation(com.baizhi.annotation.CmfzLogAnnotation)")
    public void logPointcut() {
    }

    /*写增强*/
    @After("logPointcut()")
    public void logAfter(JoinPoint joinPoint) {
        logger.debug("开始记录增强");
        /*创建日志表对应的实体类对象*/
        CmfzLog cmfzLog = new CmfzLog();
        logger.debug("创建对象成功");
        cmfzLog.setLogDate(new Date());

        /*获取session对象的方法*/
        ServletRequestAttributes requestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();

        CmfzAdmin cmfzAdmin = (CmfzAdmin) session.getAttribute("cmfzAdmin");
        logger.debug("用户对象{}",cmfzAdmin);
        cmfzLog.setAdminUsername(cmfzAdmin.getAdminUsername());
        logger.debug("用户对象获取成功");

        /*通过工具类获取ip*/
        String ipAddrByRequest =
                IPKit.getIpAddrByRequest(requestAttributes.getRequest());

        cmfzLog.setLogIp(ipAddrByRequest);

        /*通过获取当前方法上的注解 得到日志的内容*/

        // 获取方法签名对象
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();
        // 获得当前方法对象
        Method method = signature.getMethod();
        // 获取加在当前方法上的注解
        CmfzLogAnnotation annotation = method.getAnnotation(CmfzLogAnnotation.class);
        String value = annotation.value();
        cmfzLog.setLogContent(value);

        // 占位符的方式打印日志 在字符串中 写一个{} 后面使用逗号
        // 只能在logger打印中使用
        logger.info("结束记录增强:{}", cmfzLog);

        // 插入数据库
        cmfzLogDao.insert(cmfzLog);
    }
}
